<template>
  <div>
    <el-form ref="editForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="任务编号">
            <el-input v-model="formItem.code" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="巡检厅局">
            <el-input v-model="formItem.institutionName" disabled />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="执行人">
            <el-input v-model="formItem.userName" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="计划开始时间">
            <el-date-picker
              v-model="formItem.startDateTime"
              disabled
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划结束时间">
            <el-date-picker
              v-model="formItem.endDateTime"
              disabled
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="存在问题">
            <el-input v-model="formItem.problem" placeholder="请输入问题" :maxlength="2047" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="解决情况">
            <el-input v-model="formItem.solution" placeholder="请输入内容" :maxlength="2047" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="form-info-title">
            <span>现场巡检</span>
          </div>
        </el-col>
        <el-col :span="24">
          <PageableTable ref="table" :loading="false" :table-height="400" :data="formItem.itemValues" :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'left'}" :span-method="objectSpanMethod" :disable-pageable="true">
            <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
          </PageableTable>
        </el-col>
        <el-col :span="24">
          <div class="form-info-title">
            <span>资产清点</span>
          </div>
        </el-col>
        <el-col :span="24">
          <PageableTable ref="aseetTable" :loading="false" :table-height="400" :data="formItem.assets" :disable-pageable="true">
            <el-table-column v-for="column in assetColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
          </PageableTable>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import PageableTable from '@neu/biz-core/components/PageableTable'
import { update, detail, submit } from '@neu/dcom-ui/api/hnInspectionTask'
import { clone } from '@neu/biz-core/utils/utils'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
// 定义一个表单原始项
const formItem = {
  // 厅局
  institutionCode: '',
  institutionName: '',
  code: '',
  userName: '',
  userCode: '',
  startDateTime: '',
  endDateTime: '',
  solution: '',
  problem: '',
  duration: 1,
  disabled: false,
  itemValues: [],
  assets: []
}
export default {
  name: 'HnInspectionPlanEdit',
  components: {
    PageableTable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // tableData: [],
      institutions: [],
      editorOption: {},
      types: [],
      categories: [{ name: '日巡检', code: 'day' }, { name: '定期健康巡检', code: 'regular' }, { name: '重保服务', code: 'service' }],
      // 编辑的表单内容
      formItem: clone(formItem),
      // 表单验证规则
      rules: {
        // institutionCode: [{ required: true, message: '不能为空', trigger: 'change' }],
        // startDateTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
        // endDateTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
        // duration: [{ required: true, message: '持续时间不能为空', trigger: 'change' }],
        // item: [{ required: true, message: '不能为空', trigger: 'blur' }],
        // dataType: [{ required: true, message: '不能为空', trigger: 'change' }],
        // rule: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      insideColumns: [
        { title: '类别', key: 'item.itemType', display: true, render: (h, params) => {
          const status = this.types.filter(t => {
            return t.code === params.row.item.itemType
          })
          const statusDesc = status.length === 1 ? status[0].text : params.row.statusDesc
          return h('span', statusDesc)
        } },
        { title: '内容', key: 'item.item', display: true, render: (h, params) => {
          return h('span', params.row.item.item)
        } },
        { title: '结果值', key: 'value', display: true,
          render: (h, params) => {
            if (params.row.item.dataType === 'select') {
              return (
                <div>
                  <el-radio-group v-model={params.row.value}>
                    <el-radio label={'正常'}>正常</el-radio>
                    <el-radio label={'异常'}>异常</el-radio>
                  </el-radio-group>
                </div>
              )
            } else {
              return (
                <div>
                  <el-input v-model={params.row.value}/>
                </div>
              )
            }
          }
        },
        { title: '异常判断规则', key: 'item.rule', display: true,
          render: (h, params) => {
            return h('span', params.row.item.rule)
          }
        },
        { title: '异常原因', key: 'reason', display: true,
          render: (h, params) => {
            return (
              <div>
                <el-input style={ 'width:93%'} v-model={params.row.reason} placeholder='异常原因'/>
              </div>
            )
          }
        }
      ],
      assetColumns: [
        { title: '资产编号', key: 'code', display: true },
        { title: '资产分类', key: 'typeName', display: true },
        { title: '资产名称', key: 'name', display: true },
        { title: '规格型号', key: 'specification', display: true },
        { title: '存放地点', key: 'located', display: true },
        { title: '品牌', key: 'brand', display: true },
        { title: '在线状态', key: 'online', display: true, width: '200',
          render: (h, params) => {
            return (
              <div>
                <el-radio-group style={ 'width:93%'} v-model={params.row.online}>
                  <el-radio label={true}>在线</el-radio>
                  <el-radio label={false}>下线</el-radio>
                </el-radio-group>
              </div>
            )
          }
        }
      ],
      itemTypeArr: [],
      itemTypePos: 0,
      loading: null
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    findByDictionaryType('hnInspectionItemType').then(res => {
      if (res.status === 'success') {
        this.types = res.data
      }
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }

          this.formItem.itemValues = this.formItem.itemValues.sort((v1, v2) => {
            const x = v1.item.itemType.toLowerCase()
            const y = v2.item.itemType.toLowerCase()
            if (x < y) { return -1 }
            if (x > y) { return 1 }
            return 0
          })
          this.formItem.itemValues = this.formItem.itemValues.sort((v1, v2) => {
            if (v1.item.itemType === v2.item.itemType) {
              return v1.item.sort - v2.item.sort
            }
            return 0
          })
          this.merge()
          if (this.formItem.status === 'notStarted') {
            this.formItem.assets = this.formItem.assets.map(t => {
              t.online = true
              return t
            })
            this.formItem.itemValues = this.formItem.itemValues.map(t => {
              if (t.item.dataType === 'select') {
                t.value = '正常'
              }
              return t
            })
          }
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (updated) {
              let confirmText = ''
              const data = this.formItem.itemValues
              for (const i of data) {
                if (i.value && i.item.dataType === 'number') {
                  if (Number.isNaN(Number(i.value))) {
                    confirmText = i.item.item + '这条巡检项的结果必须是数值！'
                    break
                  }
                }
              }
              if (confirmText !== '') {
                return this.$message({
                  showClose: true,
                  message: confirmText,
                  type: 'error'
                })
              }
              this.loading = this.$loading({ fullscreen: true })
              resolve(update(this.id, this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    // 提交操作，返回promise，后续处理交由调用者处理
    submit() {
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            let confirmText = ''
            const data = this.formItem.itemValues
            for (const i of data) {
              if (!i.value) {
                confirmText = i.item.item + '这条巡检项的结果没有填写！'
                break
              }
              if (i.value && i.item.dataType === 'number') {
                if (Number.isNaN(Number(i.value))) {
                  confirmText = i.item.item + '这条巡检项的结果必须是数值！'
                  break
                }
              }
            }
            if (confirmText !== '') {
              return this.$message({
                showClose: true,
                message: confirmText,
                type: 'error'
              })
            }
            this.loading = this.$loading({ fullscreen: true })
            resolve(submit(this.id, this.formItem))
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.formItem = clone(this.formItem)
    },
    merageInit() {
      this.itemTypeArr = []
      this.itemTypePos = 0
    },
    merge() {
      this.merageInit()
      for (let i = 0; i < this.formItem.itemValues.length; i++) {
        if (i === 0) {
          // 第一行必须存在
          this.itemTypeArr.push(1)
          this.itemTypePos = 0
        } else {
          // 判断当前元素与上一个元素是否相同,eg：this.itemTypePos 是 this.itemTypeArr
          // 第一列
          if (this.formItem.itemValues[i].item.itemType === this.formItem.itemValues[i - 1].item.itemType) {
            this.itemTypeArr[this.itemTypePos] += 1
            this.itemTypeArr.push(0)
          } else {
            this.itemTypeArr.push(1)
            this.itemTypePos = i
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
      // 第一列的合并方法
        const row1 = this.itemTypeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0 // 如果被合并了row = 0; 则他这个列需要取消
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    tableSelection(sel) {
      this.formItem.items = sel
    },
    changeName(item) {
      this.formItem.institutionName = item.name
    }
  }
}
</script>

